package demo.icanci.pattern.singleton;

import java.lang.reflect.Constructor;

/**
 * 破坏单例设计模式
 * 
 * @author icanci
 * @date Created in 2021/02/06 00:39
 * @version 1.0
 */
public class DestructionSingleton {
    public static void main(String[] args) throws Exception {
        // 反射强无敌 但是无法破坏枚举
        Class<EnumSingleton> enumSingletonClass = EnumSingleton.class;
        Constructor<EnumSingleton> declaredConstructor = enumSingletonClass.getDeclaredConstructor(String.class,int.class);
        declaredConstructor.setAccessible(true);
        EnumSingleton enumSingleton = declaredConstructor.newInstance();
        System.out.println(enumSingleton);
    }

    private static void destruction3() throws Exception{
        // 此方式不可取
        System.out.println(EnumStarvingSingleton.getInstance());
        Class<EnumStarvingSingleton> enumStarvingSingletonClass = EnumStarvingSingleton.class;
        Constructor<EnumStarvingSingleton> co = enumStarvingSingletonClass.getDeclaredConstructor();
        co.setAccessible(true);
        EnumStarvingSingleton enumStarvingSingleton = co.newInstance();
        System.out.println(enumStarvingSingleton.getInstance());
    }
    private static void destruction2() throws Exception{
        Class<EnumStarvingSingleton> clazz = EnumStarvingSingleton.class;
        Constructor<EnumStarvingSingleton> declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        EnumStarvingSingleton ins = declaredConstructor.newInstance();
        EnumStarvingSingleton ins2 = declaredConstructor.newInstance();
        System.out.println(ins);
        System.out.println(ins2);
        System.out.println(ins == ins2);
        EnumStarvingSingleton instance = EnumStarvingSingleton.getInstance();
        System.out.println(ins == instance);
    }
    private static void destruction() throws Exception{
        Class<LazyDoubleCheckSingleton> clazz = LazyDoubleCheckSingleton.class;
        Constructor<LazyDoubleCheckSingleton> declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        LazyDoubleCheckSingleton ins = declaredConstructor.newInstance();
        LazyDoubleCheckSingleton ins2 = declaredConstructor.newInstance();
        System.out.println(ins);
        System.out.println(ins2);
        System.out.println(ins == ins2);
    }
}
